package service

import (
	"context"
	"database/sql"
	"fmt"
	"github.com/kevinlisr/install-levault/dao"
	"github.com/kevinlisr/install-levault/vari"
	"log"
	"strings"
)

type DmDbExecutor struct{}

func NewDmDbExecutor() *DmDbExecutor {
	return &DmDbExecutor{}
}

func (d *DmDbExecutor) DownloadMinioFile(ctx context.Context, db *sql.DB, mSvr *MinioExecutor, tables []string, sch, fpath string) error {
	dmdb := dao.NewDmDB(db)
	fileSvr := NewFileSvr()
	num := 0
	for _, table := range tables {
		urls, err := dmdb.QueryTable(sch, table)
		if err != nil {
			vari.Logger.Error(fmt.Sprintf("queryTable levault failed %v", urls))
			return err
		}
		for _, url := range urls {
			fileName := strings.Split(url, "/nancal/")

			vari.Logger.Error(fmt.Sprintf("%d. 数据库中获取数据：%s\n", num, fileName))
			_, err = fileSvr.CreateFile(fpath + fileName[1])
			if err != nil {
				vari.Logger.Error(fmt.Sprintf("create file %s failed!\n", fpath+fileName[1]))
				break
			}

			object, err := mSvr.DownLoadFile(ctx, "nancal", fileName[1])
			if err != nil {
				vari.Logger.Error("DownloadMinioFile failed, " + err.Error())
				return fmt.Errorf("DownloadMinioFile failed, %s", err.Error())
			}
			log.Printf("DownloadMinioFile succeeded")
			err = fileSvr.WriteFile(fpath+fileName[1], object)
			if err != nil {
				vari.Logger.Error("Write file failed, " + err.Error())
				return fmt.Errorf("Write file failed, %s", err.Error())
			}
			vari.Logger.Info("Write file succeeded")
			num += 1
			//time.Sleep(time.Second)
		}
	}
	return nil
}

/* 修改数据 */
func (d *DmDbExecutor) UpdateTable(db *sql.DB, dmlsqls []string, url string, username string,
	pwd string, dbtype string, host string, port int, miniourlOld string, miniourlNew string) error {

	dmDB := dao.NewDmDB(db)
	err := dmDB.UpdateTable(dmlsqls, url, username, pwd, dbtype, host, miniourlOld, miniourlNew, port)
	if err != nil {
		vari.Logger.Error(fmt.Sprintf("UpdateTable failed %s", err.Error()))
		return fmt.Errorf("UpdateTable failed %s", err.Error())
	}
	return nil
}

/* 关闭数据库连接 */
func (d *DmDbExecutor) Disconnect(db *sql.DB) error {
	if err := db.Close(); err != nil {
		vari.Logger.Error(fmt.Sprintf("db close failed: %s.\n", err))
		return err
	}
	vari.Logger.Info("disconnect succeed")
	return nil
}
